export default class WebsocketService {
  // 单例模式
  static instance = null
  static getInstance() {
    if (!this.instance) {
      this.instance = new this()
    }
    return this.instance
  }

  // 属性
  ws = null
  connected = false
  callbackMap = []
  closeReTryCount = 0
  openReTryCount = 0

  // 建立ws连接
  connect() {
    if (window.WebSocket) {
      this.ws = new WebSocket('ws://localhost:9998')

      // 连接成功
      this.ws.onopen = () => {
        this.connected = true
      }

      // 接收到服务器通信
      this.ws.onmessage = (res) => {
        let msgdata = JSON.parse(res.data)
        let data, socketType
        if (msgdata.action == 'getData') {
          data = JSON.parse(msgdata.data)
          socketType = msgdata.socketType
        } else {
          data = msgdata.chart
          socketType = msgdata.socketType
        }
        this.callbackMap[socketType](data)
        console.log('数据已接收...')
      }

      // 连接失败或者断开
      this.ws.onclose = () => {
        // 重连websocket
        if (!this.connected) {
          this.closeReTryCount++
          setTimeout(() => {
            this.ws = new WebSocket('ws://localhost:9998')
          }, this.closeReTryCount * 500)
        }
      }
    } else {
      console.log('您的浏览器不支持websocket, 请更换浏览器')
    }
  }

  // 向服务器发送信息
  // JSON.stringify({
  //   action: "getData",
  //   socketType: "rankData",
  //   chart: "rank",
  //   value: "",
  // }
  send(data) {
    this.ws.send(data)
  }

  // 注册vue组件回调函数(getData)，以便于onmessage时调用
  registerCallback(socketType, fn) {
    this.callbackMap[socketType] = fn
  }

  // 解除注册
  unRegisterCallback(socketType) {
    this.callbackMap[socketType] = null
  }
}
